'use strict'

/**
 * API定义
 */
//------------------------------------------------------------------
import toast from 'vant/es/toast/index'
import http from './http'
import utils from '../utils'
//------------------------------------------------------------------

export default class API {
    __http
    __apiPool
    /**
     * API类初始化方法
     */
    constructor(opts) {
        this.__http = new http({
            error: this.error,
            notLogin: this.notLogin
        })
        this.__apiPool = {
            'upload': { method: 'upload', path: 'upload', opts: { need_token: true } },
            'js_sdk_sign': { method: 'post', path: 'js_sdk_sign', opts: { need_token: false } },
            'get_config': { method: 'post', path: 'system/get_config', opts: { need_token: false } },
            'account_login': { method: 'post', path: 'auth/account_login', opts: { need_token: false } },
            'logout': { method: 'post', path: 'auth/logout', opts: { silence: true } },
            'refresh_token': { method: 'post', path: 'customer/vtuzx_refresh_token', opts: { silence: true } },
            'setting_get_options': { method: 'post', path: 'setting/dict/get_options', opts: { silence: true } },
            ...((opts && opts.pool)? opts.pool: {})
        }
    }

    /**
     * 错误处理
     */
    error(e) {
        if (typeof e === 'string') {
            toast.fail(e)    
        } else {
            toast.fail(e.message || e.err || e)
        }
    }

    /**
     * 未登录处理
     */
    notLogin() {
        let url = import.meta.env.VITE_APP_LOGIN_URL
        location.href = url
    }

    /**
     * API调用公共方法
     */
    __call(key, url, apiItem, data) {
        if (!apiItem) {
            console.log(`${ key } not exist`)
            let errMsg = '访问错误，接口不存在或无访问权限！'
            this.error(errMsg)
            return { res: false, errMsg }
        }
        switch (apiItem.method) {
            case 'post':
                return this.__http.post(url, data, apiItem.opts)
            case 'get':
                return this.__http.get(url, data, apiItem.opts)
            case 'put':
                return this.__http.put(url, data, apiItem.opts)
            case 'delete':
                return this.__http.delete(url, data, apiItem.opts)
            case 'upload':
                return this.__http.upload(url, data, apiItem.opts)
            case 'download':
                return this.__http.download(url, data, apiItem.opts)
        }
    }

    /**
     * 调用API
     */
    call(key, data) {
        let apiItem = this.__apiPool[key]
        return this.__call(key, apiItem? apiItem.path: null, apiItem, data)
    }

    /**
     * 调用API(路径带参)
     */
    callPath(key, path = {}, data) {
        let apiItem = this.__apiPool[key]
        return this.__call(key, apiItem? utils.formatString2(apiItem.path, path): null, apiItem, data)
    }
}
